<?php 
namespace town\filter;

use town\base\Filter;
use town\base\Request;
use town\dmod\DB;

class Guest implements Filter
{

    /**
     * profile 获取个人也得基础信息
     * @param  Request  $request 请求对象
     * @param  callable $next    链
     * @return 响应对象
     */
    public function doFilter(Request $request, callable $next)
    {
        $datas = $this->getInfo();
        DB::table('guest')->insert($datas);
        return $next($request);
    }


    /**
     * 获取常用信息
     */
    private function getInfo()
    {
        $data['referer']    = $_SERVER['HTTP_REFERER'];
        $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
        $data['request_url']= $_SERVER['REQUEST_URI'];
        $data['ipv4']       = $this->getIP();
        $data['create_at']  = $_SERVER['REQUEST_TIME'];
        return $data;
    }


    /**
     * 获取IP
     */
    private function getIP()  
    {  
        if ($_SERVER["HTTP_X_FORWARDED_FOR"])
            $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        else if ($_SERVER["HTTP_CLIENT_IP"])  
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        else if ($_SERVER["REMOTE_ADDR"])  
            $ip = $_SERVER["REMOTE_ADDR"];
        else if (getenv("HTTP_X_FORWARDED_FOR"))  
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("HTTP_CLIENT_IP"))  
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("REMOTE_ADDR"))  
            $ip = getenv("REMOTE_ADDR");
        else
            $ip = "Unknown";
        return $ip;  
    }

}